package com.example.exam.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.exam.entity.User;
import com.example.exam.service.UserService;
import com.example.exam.util.HttpContextUtil;
import com.example.exam.util.ResultVOUtil;
import com.example.exam.util.TokenUtil;
import com.example.exam.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author shishuqian
 * date 2021/5/12
 * time 22:28
 **/
public class UserInterceptor implements HandlerInterceptor {

 /*   @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = TokenUtil.getRequestToken(request);
        if (StringUtils.isBlank(token)){
            setReturn(response,400,"用户未登录，请先登录");
            return false;
        }

        //1.根据token，查询用户信息
        User user = userService.findByToken(token);
        //2.若用户不存在
        if (user == null){
            setReturn(response,400,"用户不存在");
            return false;
        }

        //3.token失效
        if (user.getExpireTime().isBefore(LocalDateTime.now())){
            setReturn(response,400,"用户凭证已失效，请重新登录");
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private static void setReturn(HttpServletResponse response, int status, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setStatus(400);
        response.setContentType("application/json;charset=utf-8");
        ResultVO resultVO = ResultVOUtil.common(status,msg);
        String json = JSON.toJSONString(resultVO);
        httpResponse.getWriter().print(json);
    }*/
}
